const app = getApp()
const db = wx.cloud.database()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		userInfo: ""
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		wx.cloud.callFunction({
			name: 'login',
			data: {},
			success: res => {
				console.log('[云函数] [login] user openid: ', res.result.openid)
				app.globalData.openid = res.result.openid
			},
			fail: err => {
				console.error('[云函数] [login] 调用失败', err)
			}
		})
	},
	async onGetUserInfo(e) {
		wx.getSetting({
			success: res => {
				if (res.authSetting['scope.userInfo']) {
					wx.getUserInfo({
						success: res => {
							this.setData({
								userInfo: e.detail.userInfo
							})
							app.globalData.userInfo = e.detail.userInfo
							wx.setStorageSync('userinfo', e.detail.userInfo)
              db.collection("userInfo").add({
								data: {
									userInfo: e.detail.userInfo
								}
							}).then(res => {
								wx.showLoading({
									title: '登录中',
								})
								wx.switchTab({
									url: "../daybook/daybook"
								})
							}).catch(err => {
								wx.showToast({
									title: "失败！请重试！",
									icon: "none"
								})
								setTimeout(function() {
									wx.hideLoading()
								}, 1000)
							})
						},
						fail(res) {
							console.log("获取用户信息失败", res)
						}
					})
				} else {
					wx.showModal({
						title: '提示',
						content: '为保证您的正常使用，请授权！',
					})
				}
			}
		})
	},
})